package web_config

import (
	"context"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *WebConfig {
	return new(WebConfig)
}

func (w *WebConfig) Create(db *mongo.Client) error {
	cfg := configs.Get().Mongodb
	webConfigClient := db.Database(cfg.Config.Name).Collection("web_config")
	_, err := webConfigClient.InsertOne(context.TODO(), w)
	return err
}

func (w *WebConfig) GetLast(db *mongo.Client) (WebConfig, error) {
	var webConfig WebConfig
	cfg := configs.Get().Mongodb
	findOptions := options.FindOne()
	findOptions.SetSort(bson.D{{"_id", -1}})
	webConfigClient := db.Database(cfg.Config.Name).Collection("web_config")
	err := webConfigClient.FindOne(context.TODO(), bson.D{}, findOptions).Decode(&webConfig)
	return webConfig, err
}

func (w *WebConfig) Update(db *mongo.Client) error {
	cfg := configs.Get().Mongodb
	webConfigClient := db.Database(cfg.Config.Name).Collection("web_config")
	objId, _ := primitive.ObjectIDFromHex(w.Id)
	filter := bson.M{"_id": objId}
	update := bson.M{"$set": bson.M{
		"content": w.Content,
	}}
	_, err := webConfigClient.UpdateOne(context.TODO(), filter, update)
	return err
}
